 <template>
  <mu-container>
    <div class="font_pic">
			<img v-if="refresh_img" :src="headpic" id="ex_img" class="upload_pic" :readonly="isReadonly">
			<span v-if="! isReadonly">上传行驶证的正面照片,请横向全屏摆放行驶证</span>
			<!-- capture='camera'  -->
      <input class="fileInput" accept="image/*" type="file" id="avater" name="file" @change="update" :disabled="isReadonly" />
    </div>
    <mu-form :model="form" class="mu-demo-form pa " label-position="left" label-width="100" style="padding-bottom: 80px;">

      <mu-form-item prop="select" label="车辆类型">
				<mu-flex align-items="center">
					<mu-select v-model="form.carType" :readonly="isUpdateDate">
						<mu-option v-for="(index,item) in options" :key="index" :label="index" :value="item" :readonly="isUpdateDate"></mu-option>
					</mu-select>
					<mu-button flat color="warning" v-if="isUpdateDate" @click="editInfo">修改</mu-button>
					<mu-button flat color="primary" v-if="!isUpdateDate && form.plateNum && form.registerDate" 
											@click="saveInfo">保存</mu-button>
				</mu-flex>
				<!-- <mu-button v-if="!this.order_list.orderTime" flat color="primary" @click="save_time">保存</mu-button> -->
      </mu-form-item>
      <mu-form-item prop="plateNum" label="车辆号牌" :rules="carIdRules">
        <mu-text-field v-model="form.plateNum" prop="plateNum" :readonly="isReadonly"></mu-text-field>
      </mu-form-item>
      <mu-form-item prop="vinId" label="车辆识别代号" :rules="vinIdRules">
        <mu-text-field v-model="form.vinId" prop="vinId" max-length="17" :readonly="isReadonly"></mu-text-field>
      </mu-form-item>
      <mu-form-item prop="date" label="车辆注册日期">
				<span>{{form.registerDate}}</span>
        <!-- <mu-date-input v-model="form.registerDate" container="dialog" :disabled="isReadonly"  full-width></mu-date-input> -->
      </mu-form-item>
			<mu-form-item prop="date" label="车辆使用性质">
				<!-- <mu-date-input v-model="form.registerDate" container="dialog" :disabled="isReadonly"  full-width></mu-date-input> -->
				<span>{{form.use_character}}</span>
			</mu-form-item>
			<mu-button class="editBtn" round color="success" @click="to_order">前往订单</mu-button>
			<!-- <mu-button class="nextBtn" @click="to_next" v-if="isSave" color="primary">保存</mu-button> -->
			<mu-button class="reset" @click="resetForm">重置</mu-button>
			<mu-circular-progress v-if="this.loading" class="loading demo-circular-progress" :size="36" text="图片解析中">
			</mu-circular-progress>
			<div class="alert-demo-wrapper">
				<mu-alert color="warning" @delete="alert1 = false" delete v-if="alert1" transition="mu-scale-transition">
					<mu-icon left value="warning"></mu-icon>{{alert_msg}}
				</mu-alert>
			</div>
			<div class="alert-demo-wrapper">
				<mu-alert color="warning" @delete="alert2 = false" delete v-if="alert2" transition="mu-scale-transition">
					<mu-icon left value="warning"></mu-icon>{{alert_msg2}}
				</mu-alert>
			</div>
    </mu-form>
    <mu-dialog title="提示信息" width="360" :open.sync="openSimple">
      {{msg}}
      <mu-button slot="actions" flat color="primary" @click="closeSimpleDialog">关闭</mu-button>
    </mu-dialog>
  </mu-container>


</template>

<script>
    export default {
        name: "app_form",
      data () {
        return {
					alert1: false,
					alert_msg: '',
					alert2: false,
					alert_msg2: '',
					orderId: '',
					orderMoney: undefined,
					refresh_img: true,
					isUploadImg: false,
					isReadonly: false,
					isSave: false,
					isUpdateDate: false,
					carIdRules: [
						{validate: (val) => !!val, message: '必须填写车牌号'},
						{validate: (val) => this.isLicensePlate(val), message: '车牌号有误'}
					],
					vinIdRules: [
						{validate: (val) => !!val, message: '必须填写车辆识别代号'},
						{validate: (val) => val.length == 17 , message: '请正确输入17位的车辆识别代号'}
					],
          options: {
            5:'五座汽车',
            7:'七座汽车'
          },
          msg:"",
          openSimple: false,
          labelPosition: 'left',
          form: {
            carType: '',
            plateNum: '',
            vinId: '',
            registerDate: '',
						use_character:''

          },
          loading: false,
					operateCar: '1',
          headpic: '/static/images/camera-iris.png'
        }
      },
      methods: {
				/**
				 * 前往订单
				 */
				to_order(){
					if(this.$route.query.orderId){
						// 支付页面
						this.$router.push({name:'order',query:{orderId: this.$route.query.orderId,orderMoney: this.orderMoney}})
					}else{
						this.$router.push({name:'order_list'})
					}
					
				},
				/**
				 * 修改类型
				 */
        editInfo(){
					this.isUpdateDate = false
        },
				/**
				 * 保存类型
				 */
				saveInfo(){
					if(this.form.carType == ''){
						this.$toast.error('请选择您的车辆类型')
						return
					}
					this.$ajax.post("/check-car/app/check/user/addUserCar", {
						"carType": this.form.carType == '五座汽车'?5:7,
						"plateNum": this.form.plateNum,
						"vinId": this.form.vinId,
						"registerDate": this.form.registerDate
						// "operateCar": this.operateCar
					}).then((res)=> {
            if (res.data.code ==200){
							this.isUpdateDate = true
							this.$toast.success('修改成功')
            }else if (res.data.code == 500){
							this.$toast.error(res.data.msg)
            }
          });
					
				},
				/**
				 * 重置
				 */
				resetForm(){
					this.headpic='/static/images/camera-iris.png'
					this.form.carType=''
					this.form.plateNum=''
					this.form.vinId=''
					this.form.registerDate=''
					this.form.use_character=''
					this.isReadonly=false
					this.isSave = true
					this.$toast.info("请重新上传行驶证照片");
				},
				// 驾驶证校验
				isLicensePlate(str) {
					return /^(([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z](([0-9]{5}[DF])|([DF]([A-HJ-NP-Z0-9])[0-9]{4})))|([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳使领]))$/.test(str)
				},
        closeSimpleDialog () {
          this.openSimple = false;
        },
				/**
				 * 上传行驶证
				 */
				upload_img(base64Data,base64Len){
					this.$ajax.post('/check-car/app/check/uploadCarPic',
						{"base64Data":base64Data,"base64Len":base64Len,"orderId": this.orderId},
						{timeout: 12000}).then((res)=>{
							if(res.data.code == 200){
								// setTimeout("window.location.reload()",2000);
								// console.log(new Date())
								this.loading = false;
								this.form.plateNum = res.data.plate_num
								this.form.vinId = res.data.vin
								this.form.registerDate = res.data.register_date
								this.form.use_character = res.data.use_character
								this.headpic = "/static/images/模糊.jpg"
								if(res.data.orderMoney){
									// 订单修改
									this.orderMoney = res.data.orderMoney
									this.alert1 = !this.alert1;
									this.alert2 = !this.alert2;
									this.alert_msg = '行驶证上的车辆使用性质与您下单时候的选择不一样'
									this.alert_msg2 = '系统以您行驶证上信息为准，修改订单价格为:'+res.data.orderMoney
								}
								this.$toast.success('选择您的车辆类型');
								this.isSave=true
							}else if (res.data.code == 500) {
								this.loading = false;
								this.openSimple = true;
								this.msg = res.data.msg;
							}else if(res.data.code ==401){
								setTimeout(this.$router.push({name: 'login'}),1000);
								this.$toast.info("登陆失效，请重新登陆");
							}
						}).catch(() => {
							if(this.loading == false){
								this.$toast.error('请求超时，刷新重试')
								console.log('超时')
							}
						})
				},
				/**
				 * 获取行驶证照片
				 */
        update(e){
          this.$toast.info('5秒内若如结果，可刷新重试')
          let file = e.target.files[0];
//           let param = new window.FormData(); //创建form对象
//           param.append('file',file);//通过append向form对象添加数据
					// console.log(new Date())
					console.log(file)
					this.loading = true;
					// 压缩上传
					this.lrz_img(file,0.8)
        },
				/**
				 * 压缩行驶证照片
				 */
				lrz_img(file,quality){
					if(file.size == 0){
						this.$toast.error('文件为空');
						return
					}
					let i = parseInt(file.size/1024)
					console.log('文件大小/kb:'+i)
					this.$toast.info("上传文件大小："+i+"/KB,压缩中...");
					// quality = 0.05
					if(i < 1024){
						// 上传
						quality = 0.7
					}else if( i > 1024 && i < 5200){
						quality = 0.08
					}else{
						quality = 0.08
					}
						lrz(file,{
							width: 2000,
							heigh: 1500,
							quality: quality
						}).then((res) => {
							console.log(res)
							console.log(parseInt(res.fileLen/1024))
							this.$toast.info("压缩成功："+parseInt(res.fileLen/1024)+"/KB,开始上传...");
							this.upload_img(res.base64,res.base64Len)
							// this.loading = false;
							
						}).catch((res) => {
							this.$toast.error('压缩失败');
							// this.upload_img(res.base64,res.base64Len)
							this.loading = false;
						})
					
				}
      },
      created(){
				let userInfo = JSON.parse(localStorage.getItem('USER'));
				if(!userInfo){
					this.$router.push({name: 'login'})
				}else{
					let nowdate = new Date()
					if((nowdate.getTime() - userInfo.date)/1000 > userInfo.expire){
						localStorage.clear()
						this.$router.push({name: 'login'})
					}
				}
				this.orderId = this.$route.query.orderId
        this.$ajax.get("/check-car/app/check/user/getCarInfo", {
        }).then((res)=> {
					 console.log(res)
          if (res.data.code ==200){
						console.log(res.data)
            this.isReadonly = true;
						this.isUpdateDate = true
            this.form.carType = res.data.carInfo.carType==5?'五座汽车':'七座汽车';
            this.form.plateNum = res.data.carInfo.plateNum;
            this.form.vinId = res.data.carInfo.vin;
            this.form.registerDate = res.data.carInfo.registerDate;
						this.form.use_character = res.data.carInfo.useCharacter;
						this.headpic = "/static/images/模糊.jpg"
						
						this.orderId = this.$route.query.orderId
            // this.headpic = 'http://localhost:8080/check-car/app/sms/showCarPic/'+res.data.carInfo.userId+'/'+res.data.carInfo.plateNum;
            // this.operateCar = JSON.stringify(res.data.carInfo.operateCar);
						
          }else if(res.data.code ==401){
						// setTimeout(this.$router.push({name: 'login'}),3000);
						this.$toast.info("登陆失效，请重新登陆");
					}
					else if(res.data.code ==500){
						console.log(res.data.msg)
						// Toast.info('请先上传照片');
						this.$toast.info(res.data.msg);
					}
        });
      }
    }
</script>

<style scoped>
.font_pic{
  margin-bottom: 2rem;
  height: 10rem;
  /* background-color: #ffa2c4; */
}

.upload_pic{
	width: 100%;
	height: 100%;
}
.font_pic span{
	margin-left: 10%;
	margin-top: 21%;
	font-size: 14px;
	font-weight: 500;
}
/* .font_pic img{
  width: 100%;
  height: 100%;
} */
.nextBtn{
	height: 100%;
  margin-left: 15px;
  width: 90%;
}

.reset{
	height: 100%;
	margin-top: 10px;
	margin-left: 15px;
	width: 90%;
}

.editBtn{
	height: 100%;
	margin-bottom: 10px;
  margin-left: 30%;
  width: 40%;
}
.suporse{
  margin: 0.5rem auto;
  text-align: center;
}
/*定义上传*/
.fileInput{

  width: 98%;
  height: 160px;
  position: absolute;
  right: 0;
  top: 72px;
  opacity: 0
}
.loading{
  position: absolute;
  left: 50%;
  top: 50%;
  z-index: 9999;
}
.alert-demo-wrapper {
  width: 100%;
  > .mu-alert {
    margin-bottom: 16px;
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.mu-scale-transition-enter-active,
.mu-scale-transition-leave-active {
  transition: transform .45s cubic-bezier(0.23, 1, 0.32, 1), opacity .45s cubic-bezier(0.23, 1, 0.32, 1);
  backface-visibility: hidden;
}

.mu-scale-transition-enter,
.mu-scale-transition-leave-active {
  transform: scale(0);
  opacity: 0;
}

</style>
